//
//  JXHComposeViewController.swift
//  JXHSinaWeiBo
//
//  Created by juxiaohui on 16/10/27.
//  Copyright © 2016年 juxiaohui. All rights reserved.
//

import UIKit
import TZImagePickerController
import SVProgressHUD

class JXHComposeViewController: UIViewController {

    lazy var titleView : JXHComposeTitleView = JXHComposeTitleView()
    
    lazy var images : [UIImage] = [UIImage]()
    
    lazy var emoticonVC : JXHEmoticonController = JXHEmoticonController.init { [weak self] (emoticon) in
        //从写构造函数初始化时代个闭包 、、注意循环引用
        
        self?.textView.insertEmoticon(emoticon : emoticon)
        self?.textViewDidChange(self!.textView)
    }

    
    @IBOutlet weak var textView: JXHComposeTextView!
    
    @IBOutlet weak var toolbar: UIToolbar!
    
    @IBOutlet weak var toolbarBottomConstraint: NSLayoutConstraint!
    
    @IBOutlet weak var picturePickerView: JXHPicturePickerCollectionView!
    
    @IBOutlet weak var collectionViewHConstraint: NSLayoutConstraint!
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
    
        setupNav()
        setupNotifications()
    }
    

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        textView.becomeFirstResponder()
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        textView.resignFirstResponder()
    }
    
    
    // 销毁时调用
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
}

// MARK: - UI 界面
extension JXHComposeViewController {
    
    
    func setupNotifications() {
        
        //监听通知
        let noteName = Notification.Name.UIKeyboardWillChangeFrame
        
        NotificationCenter.default.addObserver(self, selector: #selector(JXHComposeViewController.keyboardWillChangeFrame(note:)) , name: noteName, object: nil)
        
        NotificationCenter.default.addObserver(self, selector: #selector(JXHComposeViewController.addPhotoBtnClickNote), name: NSNotification.Name.init(picturePickerAddPhoto), object: nil)
    
        NotificationCenter.default.addObserver(self, selector: #selector(JXHComposeViewController.removePhotoBtnClickNote(note:)), name: NSNotification.Name.init(picturePickerRemovePhoto), object: nil)
    }
    
    func setupNav() {
        
        navigationItem.leftBarButtonItem = UIBarButtonItem.init(title: "关闭", style: .plain, target: self, action: #selector(JXHComposeViewController.closeItemClick))
        navigationItem.rightBarButtonItem = UIBarButtonItem.init(title: "发布", style: .plain, target: self, action: #selector(JXHComposeViewController.sentItemClick))
        navigationItem.rightBarButtonItem?.isEnabled = false
        titleView.frame = CGRect.init(x: 0, y: 0, width: 300, height: 40)
        navigationItem.titleView = titleView
        
    }
}

// MARK: - 事件监听
extension JXHComposeViewController {
    
    @IBAction func picPickerBtnClick() {
        
        textView.resignFirstResponder()
        
        view.addSubview(toolbar)
        
        collectionViewHConstraint.constant = UIScreen.main.bounds.height * 0.65
        UIView.animate(withDuration: 0.5) {
            
            self.view.layoutIfNeeded()
        }
    }
    
    @IBAction func emoticonBtnClick(_ sender: UIButton) {
    
        //切换键盘相关逻辑
        textView.resignFirstResponder()
        
        textView.inputView = textView.inputView != nil ? nil : emoticonVC.view
        
        textView.becomeFirstResponder()
    }
    
    
    func closeItemClick() {
        
        dismiss(animated: true, completion: nil)
    }
    
    func sentItemClick() {
        
        textView.resignFirstResponder()
        
        let text = textView.getEmoticonString()
        
        //定义回调闭包
        let finishedCallBack = { (isSuccess : Bool) in
            if isSuccess {
                SVProgressHUD.showSuccess(withStatus: "发送成功")
                self.dismiss(animated: true, completion: nil)
            }else{
                SVProgressHUD.showSuccess(withStatus: "发送失败")
            }
        }

        if let image = images.first{
            JXHNetWorkTools.shareInstance.sentStatus(text: text, image: image, isSuccess: finishedCallBack)
        }else{
            JXHNetWorkTools.shareInstance.sentStatus(text: text ,isSuccess: finishedCallBack)
        }
    }
    
    func keyboardWillChangeFrame(note : Notification)  {
    
        // 获取动画执行的时间
        let duration = note.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! TimeInterval
       //得到键盘的Y值
        
        let endFrame = (note.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
        let y = endFrame.origin.y
        
        //计算工具栏距离底部的间距
        
        let margin = UIScreen.main.bounds.height - y
        
        //执行动画
        toolbarBottomConstraint.constant = margin
        
        UIView.animate(withDuration: duration) { 

            self.view.layoutIfNeeded()
        }
    }
    
    func addPhotoBtnClickNote() {
        
        let  imagePickerVc = TZImagePickerController.init(maxImagesCount: 9, delegate: self)
        imagePickerVc?.isSelectOriginalPhoto = true
        imagePickerVc?.allowTakePicture = false
        imagePickerVc?.allowPickingVideo = true
        imagePickerVc?.allowPickingImage = true
        imagePickerVc?.allowPickingOriginalPhoto = true
        present(imagePickerVc!, animated: true, completion: nil)
    }
    
    
    func removePhotoBtnClickNote(note : Notification) {
        
        guard let image = note.object as? UIImage else {
            return
        }
        
        guard let index = images.index(of: image) else{
            return
        }
        
        images.remove(at: index)
        picturePickerView.images = images
    }
}

// MARK: - TZImagePickerControllerDelegate

extension JXHComposeViewController : TZImagePickerControllerDelegate {

    func imagePickerController(_ picker: TZImagePickerController!, didFinishPickingPhotos photos: [UIImage]!, sourceAssets assets: [Any]!, isSelectOriginalPhoto: Bool) {

        images = photos
        
        picturePickerView.images = images
    }
    
    func imagePickerControllerDidCancel(_ picker: TZImagePickerController!) {
       // self.dismiss(animated: (picker != nil), completion: nil)
    }
}



// MARK: - UITextViewDelegate

extension JXHComposeViewController : UITextViewDelegate {
    
    //文字发生改变
    func textViewDidChange(_ textView: UITextView) {
        self.textView.placeHolderLabel.isHidden = textView.hasText
        navigationItem.rightBarButtonItem?.isEnabled = textView.hasText
    }
    
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
        textView.resignFirstResponder()
    }
}


// MARK: - 自定义NSTextAttachment
class JXHTextAttachment : NSTextAttachment {
    
    var chs : String?
    
}

